/*
 * @Author: pardon110
 * @Date: 2024-03-25 17:39:09
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-26 10:23:25
 * @FilePath: \days7\orm\sqlop\engine.go
 * @Description:
 */
package sqlop

import (
	"database/sql"

	"days7.test/orm/log"
	"days7.test/orm/sqlop/session"
)

type Engine struct {
	db *sql.DB // private
}

// NewEngine connect database and ping it to test whether it's alive
func NewEngine(driver, source string) (e *Engine, err error) {
	db, err := sql.Open(driver, source)
	if err != nil {
		log.Error(err)
		return
	}

	// keep alive test connection
	if err = db.Ping(); err != nil {
		log.Error(err)
		return
	}

	e = &Engine{db: db}
	log.Info("connect database success")
	return
}

func (e *Engine) Close() {
	if err := e.db.Close(); err != nil {
		log.Error("failed to close database")
	}
	log.Info("close database success")
}

// session 与 连接分离
func (e *Engine) NewSession() *session.Session {
	return session.New(e.db)
}
